package com.biomatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biomatch.domain.Role;
import com.biomatch.dto.Pagination;
import com.biomatch.mapper.RoleMapper;
import com.biomatch.service.RoleService;
import com.biomatch.utils.Internationalize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private Internationalize internationalize;

    @Override
    public List<Role> getAllRoles() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        return roleMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<Role> getRolesByPage(Pagination pagination) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        IPage<Role> iPage = new Page<>(pagination.getCurrent(), pagination.getPageSize());
        return roleMapper.selectPage(iPage, queryWrapper);
    }

    @Override
    public Role saveOrUpdateRole(Role role) {
        if (role.getRoleId().equals("new")) {
            if (roleMapper.selectOneByName(role.getName()) != null) {
                return null;
            }
        } else {
            if (roleMapper.selectOneNotCodeIsName(role.getRoleId(), role.getName()) != null) {
                return null;
            }
        }
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleId", role.getRoleId()).orderByDesc("id").last("limit 1");
        Role other = roleMapper.selectOne(queryWrapper);
        if (other == null) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            role.setRoleId("R" + sdf.format(date));
            roleMapper.insert(role);
            return role;
        } else {
            other.setName(role.getName());
            roleMapper.updateById(other);
            return other;
        }
    }

    @Override
    public Role deleteRole(Role role) {
        if(role.getId()!=0 && role.getRoleId()!=null && role.getName()!=null && !role.getRoleId().equals("") && !role.getName().equals(""))
        {
            roleMapper.deleteById(role.getId());
        }
        else
        {
            return null;
        }
        return role;
    }


}